﻿#include "cAISettings.h"

cAISettings::cAISettings( cSoldierData* soldierData )
{
	_pSoldierData = soldierData;
	Init();
}

void cAISettings::Init()
{
	_bToClose = false;
	_bClearSight = false;
	_bSpawnBullet = false;
}

void cAISettings::Update( cMap* map, cSoldierData* player02 )
{
	//Check the distance between the soldiers
	int tmpDistance = distanceBetweenPoints( _pSoldierData->GetPosition(), player02->GetPosition() );
	if( tmpDistance < _nToCloseAlertDistance )
	{
		if( !_bToClose )
			cMessageBoxInGame::GetInstance()->AddMessage( _cToCloseString );
		_bToClose = true;
	}
	else
	{
		if( _bToClose )
			cMessageBoxInGame::GetInstance()->AddMessage( _cNotToCloseString );
		_bToClose = false;
	}

	//Check if sight is clear between the soldiers
	if( IsClearSight( 
			map, 
			cMapPositionHelper::PixelToSquarePos( _pSoldierData->GetPosition() ),
			cMapPositionHelper::PixelToSquarePos( player02->GetPosition() ) ) )
	{
		if( !_bClearSight )
			cMessageBoxInGame::GetInstance()->AddMessage( "The sight between the soldiers is now clear." );
		_bSpawnBullet = true;
		_bClearSight = true;
	}
	else
	{
		if( _bClearSight )
			cMessageBoxInGame::GetInstance()->AddMessage( "The sight between the soldiers is no longer clear." );
		_bSpawnBullet = false;
		_bClearSight = false;
	}
}

bool cAISettings::IsClearSight( cMap* map, vector2d<s32> p1, vector2d<s32> p2 )
{
	int deltaX = p2.X - p1.X;
	int deltaY = p2.Y - p1.Y;
    float error, deltaerr  = 0.f;
	int y = p1.Y;
	int x = p1.X;

	if( deltaX != 0 ) //Non-vertical line
	{
		deltaerr = abs (deltaY / deltaX);
		while( x != p2.X )
		{
			if( !map->IsPosWalkable( vector2d<s32>(x, y) ) )
				return false;

			error += deltaerr;
			if( error >= 0.5 )
			{
				y++;
				error += 1.0;
			}
			x++;
		}
	}
	else //Vertical line
		while( y != p2.Y )
		{
			if( !map->IsPosWalkable( vector2d<s32>(x, y) ) )
				return false;
			y++;
		}
	return true;
}

void cAISettings::SetToCloseAlertDistance( int distance )
{
	 _nToCloseAlertDistance = distance;

	char integerString[32];
	std::sprintf(integerString, "%d", _nToCloseAlertDistance);
	char tmpString01[64] = "The enemy is within your specified alertrange. (";
	std::strcat(tmpString01, integerString);
	std::strcat(tmpString01, ")");
	std::strcpy(_cToCloseString, tmpString01);

	char tmpString02[64] = "The enemy is no longer within your specified alertrange. (";
	std::strcat(tmpString02, integerString);
	std::strcat(tmpString02, ")");
	std::strcpy(_cNotToCloseString, tmpString02);
}

irr::s32 cAISettings::distanceBetweenPoints( vector2d<s32> p1, vector2d<s32> p2 )
{
	float width = (float)abs( p2.X - p1.X );
	float height = (float)abs( p2.Y - p1.Y );
	float hyp = sqrtf( width*width + height*height );
	return floor32( hyp );
}